package pl.un4giv3n.mightvsmagic.admin.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.User;

public class SearchUserAction extends PersistenceAction{
	private static final long serialVersionUID = 1L;
	private Long id;
	private String username;
	private String email;
	private User searchedUser;
	//data for jsp
	private List<User> players = new ArrayList<User>();
	private List<User> admins = new ArrayList<User>();
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		Query adminQuery = entityManager.createNamedQuery("find.admins");
		admins = adminQuery.getResultList();
		searchedUser = null;
		if(id != null){
			 searchedUser = findUserById(entityManager);
		}else if (username != null && !"".equals(username.trim())){
			searchedUser = findUserByLogin(entityManager);
		}else if (email != null && !"".equals(email.trim())){
			searchedUser = findUserByEmail(entityManager);
		}else{
			addActionError("Brak parametrów wyszukiwania");
			entityManager.close();
			return SUCCESS;
		}
		if(searchedUser == null){
			addActionError("Nie znaleziono gracza");
			entityManager.close();
			return SUCCESS;
		}
		players = Collections.singletonList(searchedUser);
		entityManager.close();
		return SUCCESS;
	}
	@SuppressWarnings("unchecked")
	private User findUserByEmail(EntityManager entityManager) {
		Query query = entityManager.createNamedQuery("admin.find.user.by.email");
		query.setParameter("email", email);
		List<User> users = query.getResultList();
		if(users.isEmpty()){
			return null;
		}else{
			return users.get(0);
		}
	}
	@SuppressWarnings("unchecked")
	private User findUserByLogin(EntityManager entityManager) {
		Query query = entityManager.createNamedQuery("admin.find.user.by.login");
		query.setParameter("login", username);
		List<User> users = query.getResultList();
		if(users.isEmpty()){
			return null;
		}else{
			return users.get(0);
		}
	}
	private User findUserById(EntityManager entityManager) {
		return entityManager.find(User.class, id);
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public List<User> getPlayers() {
		return players;
	}
	public List<User> getAdmins() {
		return admins;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}

}
